class Solution {
public:
    int maxSubarraySumCircular(vector<int>& nums)
    {
        int n = nums.size();
        int gmin = INT_MAX, fmax = INT_MIN, sum = 0;
        vector<int> f(n + 1), g(n + 1);
        for (int i = 1; i <= n; i++)
        {
            f[i] = max(nums[i - 1], f[i - 1] + nums[i - 1]);
            fmax = max(f[i], fmax);
            g[i] = min(nums[i - 1], g[i - 1] + nums[i - 1]);
            gmin = min(g[i], gmin);
            sum += nums[i - 1];
        }

        return gmin == sum ? fmax : max(sum - gmin, fmax);


    }
};